package com.mengyan.manage.cms.service.Impl;

import com.mengyan.framework.domain.cms.CmsTemplate;
import com.mengyan.framework.domain.cms.request.QueryTemplateRequest;
import com.mengyan.framework.model.response.CommonCode;
import com.mengyan.framework.model.response.QueryResponseResult;
import com.mengyan.framework.model.response.QueryResult;
import com.mengyan.framework.model.response.ResponseResultBase;
import com.mengyan.manage.cms.dao.CmsTemplateRepository;
import com.mengyan.manage.cms.service.TemplateService;
import org.apache.commons.lang3.StringUtils;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.mongodb.gridfs.GridFsTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.List;

@Service
public class TemplateServiceImpl  implements TemplateService{

    private final CmsTemplateRepository cmsTemplateRepository;

    private final GridFsTemplate gridFsTemplate;

    @Autowired
    public TemplateServiceImpl(CmsTemplateRepository cmsTemplateRepository, GridFsTemplate gridFsTemplate) {
        this.cmsTemplateRepository = cmsTemplateRepository;
        this.gridFsTemplate = gridFsTemplate;
    }

    @Override
    public QueryResponseResult findAll() {
        List<CmsTemplate> list = cmsTemplateRepository.findAll();

        QueryResult queryResult = new QueryResult();
        queryResult.setList(list);
        queryResult.setTotal(list.size());
        return new QueryResponseResult(CommonCode.SUCCESS,queryResult);
    }


    @Override
    public QueryResponseResult findList(int page, int size, QueryTemplateRequest queryTemplateRequest) {
        if(queryTemplateRequest == null) {
            queryTemplateRequest = new QueryTemplateRequest();
        }
        ExampleMatcher exampleMatcher = ExampleMatcher.matching()
                .withMatcher("templateName",ExampleMatcher.GenericPropertyMatchers.contains());
        CmsTemplate cmsTemplate = new CmsTemplate();
        if(StringUtils.isNotEmpty(queryTemplateRequest.getSiteId())) {
            cmsTemplate.setSiteId(queryTemplateRequest.getSiteId());
        }
        if(StringUtils.isNotEmpty(queryTemplateRequest.getTemplateName())) {
            cmsTemplate.setTemplateName(queryTemplateRequest.getTemplateName());
        }
        Example<CmsTemplate> example = Example.of(cmsTemplate,exampleMatcher);
        if(page < 1) {
            page = 1;
        }
        Pageable pageable = PageRequest.of(page-1,size);
        Page<CmsTemplate> pages = cmsTemplateRepository.findAll(example,pageable);
        QueryResult queryResult = new QueryResult();
        queryResult.setList(pages.getContent());
        queryResult.setTotal(pages.getTotalElements());
        QueryResponseResult queryResponseResult = new QueryResponseResult(CommonCode.SUCCESS,queryResult);
        return queryResponseResult;
    }

    @Override
    public String save(MultipartFile[] multipartfiles) throws IOException {
        if(multipartfiles != null && multipartfiles.length == 1) {
            MultipartFile item = multipartfiles[0];
            File f = null;
            if(item.equals("")||item.getSize()<=0){
                item = null;
            }else{
                InputStream ins = item.getInputStream();
                f=new File(item.getOriginalFilename());
                inputStreamToFile(ins, f);
            }
            FileInputStream fileInputStream = new FileInputStream(f);
            ObjectId store = gridFsTemplate.store(fileInputStream, item.getName());
            String id = store.toString();
            System.out.println(id);
            File del = new File(f.toURI());
            del.delete();
            return id;
        } else {
            return null;
        }
    }

    @Override
    public ResponseResultBase<CmsTemplate> add(CmsTemplate cmsTemplate) {
        cmsTemplate.setTemplateId(null);
        CmsTemplate save = cmsTemplateRepository.save(cmsTemplate);
        return new ResponseResultBase<CmsTemplate>(CommonCode.SUCCESS,save);
    }

    private static void inputStreamToFile(InputStream ins, File file) {
        try {
            OutputStream os = new FileOutputStream(file);
            int bytesRead = 0;
            byte[] buffer = new byte[8192];
            while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
            os.close();
            ins.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
